package net.dl.ss.web;

import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
public class ResourceBundleHelper {
	private String basename;
	private String language;
    private String country;
    private String bundle;
    
    public String getMessage(String key) {
		return ResourceBundle.getBundle(basename, getDefaultLocale()).getString(key);
    }
    
    public String getBundle() {
		if(bundle == null) {
			StringBuffer ret = new StringBuffer("{");
	        Locale locale = getDefaultLocale();
	        
	        for (Enumeration enumr = ResourceBundle.getBundle(basename, locale).getKeys(); enumr.hasMoreElements(); ) {
	        	String key = (String) enumr.nextElement();
	            String value = (String) ResourceBundle.getBundle(basename, locale).getString(key);
	            key = key.replace('.', '_') + ": ";
	            ret.append(key);
	            ret.append("'" + value + "'");
	            if (enumr.hasMoreElements()) {
	            	ret.append(", ");
	            }
	        }
	        ret.append("}");
	        bundle = ret.toString();
		}
        return bundle;
    }

	
	
    private Locale getDefaultLocale(){
        return getLocale(language, country);
    }

    private Locale getLocale(String language, String country){
    	Locale ret = null;
        if(language!=null && country!= null){
            ret = new Locale(language,country);
        }else if(language != null){
            ret = new Locale(language);
        }else{
            ret = Locale.getDefault();
        }
        return ret;
    }

    public void setBasename(String basename) {
        this.basename = basename;
    }
    
    public void setLanguage(String language) {
        this.language = language;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    
}
